<template>
  <el-dialog
      top="10vh"
      width="700px"
      title="添加/编辑采购单"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        @change="handleFormChange"
        @save="onSave"
        @close="dialogValue = false"
    />
  </el-dialog>
</template>

<script>
import {http} from '@/api'
import dayjs from 'dayjs'
export default {
  name: 'DailyMenuFormAdd',
  data() {
    return {
      apiKey: 'dailyMenu',
      dialogValue: false,
      ruleForm: {},
      defaultForm: {
        menu_date: '',
        title: '',
        description: '',
        supplier_id: '',
        purchaser_id: '',
        status: 0
      },
      rules: {
        menu_date: [
          {required: true, message: '菜单日期不能为空', trigger: 'blur'}
        ],
        title: [
          {required: true, message: '菜单标题不能为空', trigger: 'blur'},
          {min: 2, max: 255, message: '菜单标题长度在 2 到 255 个字符', trigger: 'blur'}
        ],
        description: [
          {max: 1000, message: '菜单描述长度不能超过1000个字符', trigger: 'blur'}
        ],
        supplier_id: [
          {required: true, message: '请选择供应商', trigger: 'blur'}
        ],
        purchaser_id: [
          {required: true, message: '请选择采购员', trigger: 'blur'}
        ]
      },
      formList: [
        {
          label: '菜单日期',
          prop: 'menu_date',
          name: 'datetime',
          dateType: 'date',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '请选择菜单日期',
          colSpan: 12
        },
        {
          label: '菜单标题',
          prop: 'title',
          name: 'input',
          placeholder: '请输入菜单标题',
          colSpan: 12
        },
        {
          label: '供应商',
          prop: 'supplier_id',
          name: 'select',
          placeholder: '请选择供应商',
          colSpan: 12,
          options: []
        },
        {
          label: '采购员',
          prop: 'purchaser_id',
          name: 'select',
          placeholder: '请选择采购员',
          colSpan: 12,
          options: []
        },
        {
          label: '菜单描述',
          prop: 'description',
          name: 'textarea',
          placeholder: '请输入菜单描述（选填）',
          colSpan: 24,
          rows: 3
        },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          colSpan: 12,
          options: [
            { value: 0, label: '草稿' },
            { value: 1, label: '待采购' },
            { value: 2, label: '采购中' },
            { value: 3, label: '已收货' },
            { value: 4, label: '已完成' }
          ]
        }
      ]
    }
  },
  methods: {
    handleFormChange({key, val}) {
      // 处理表单变化
      console.log('表单字段变化:', key, val);
      if (key === 'menu_date') {
        this.ruleForm.supplier_id = ''
        this.formList.find(field => field.prop ==='supplier_id').options = []
        if (!val) {
          this.formList.find(field => field.prop === 'supplier_id').options = []
          return
        }
        this.loadSuppliers();
      }
    },

    async loadSuppliers() {
      try {
        const monthlyBidding = await http.monthlyBidding.list({
            month: dayjs(this.ruleForm.menu_date).format('YYYY-MM'),
            status: 3
        })
        if (monthlyBidding.data.length > 0) {
            let _monthlyBidding = monthlyBidding.data[0]

            // 更新供应商选项
            const supplierField = this.formList.find(field => field.prop === 'supplier_id');
            if (supplierField && _monthlyBidding.supplier) {
              supplierField.options = [
                {
                  value: _monthlyBidding.supplier.id,
                  label: _monthlyBidding.supplier.name
                }
              ]
              this.ruleForm.supplier_id = _monthlyBidding.supplier.id
            } else {
              this.$message.error('该月份未确定供应商，请先确定供应商');
            }
        } else {
          this.$message.error('该月份未确定供应商，请先确定供应商');
        }

      } catch (error) {
        console.error('加载供应商列表失败:', error);
      }
    },

    async loadPurchasers() {
      try {
        const res = await http.purchaser.list();
        const purchasers = res.data || [];
        const purchaserOptions = purchasers.map(purchaser => ({
          value: purchaser.id,
          label: purchaser.name
        }));

        // 更新采购员选项
        const purchaserField = this.formList.find(field => field.prop === 'purchaser_id');
        if (purchaserField) {
          purchaserField.options = purchaserOptions;
        }
      } catch (error) {
        console.error('加载采购员列表失败:', error);
      }
    },

    open(row) {
      this.dialogValue = true

      // 加载供应商和采购员列表
      this.loadPurchasers();

      if (row) {
        // 编辑模式
        http[this.apiKey].read(row.id).then(res => {
          this.ruleForm = {
            ...res.data
          }
          this.handleFormChange({key: 'menu_date', val: this.ruleForm.menu_date})
        })
      } else {
        // 新增模式
        this.ruleForm = {
          ...this.defaultForm
        }
      }
    },

    onSave() {
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, this.ruleForm).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      }).catch(error => {
        console.error('保存失败:', error);
        this.$message.error('操作失败: ' + (error.message || '未知错误'));
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
